#include "networkcontroller.h"
#include <QJsonDocument>
#include <QJsonObject>
#include <QDebug>
#include <QMessageBox>
#include"Config.h"
#include "pagecontroller.h"
#include "friendpage.h"
#include "userinfo.h"

NetWorkController NetWorkController::instance;

QJsonObject parseJsonString(const QString& jsonString) {
    // 1. 去除前后的无用字符
    QString trimmedJsonString = jsonString.trimmed();
    trimmedJsonString = trimmedJsonString.remove(QRegExp("^\\x00+|\\x00+$"));

    // 2. 解析 JSON 字符串为 QJsonObject
    QJsonDocument doc = QJsonDocument::fromJson(trimmedJsonString.toUtf8());
    if (doc.isObject()) {
        return doc.object();
    } else {
        return QJsonObject();
    }
}
void NetWorkController::m_connetToServer()
{
    quint16 port = 8080;
    cSocket->connectToHost(QHostAddress(HOSTNAME),HOSTPORT);
    if (!cSocket->waitForConnected(5000)) {
        QString errorString = cSocket->errorString();
        qCritical() << "Failed to connect to the server:" << errorString;
        isConnect = false;
    }else{
        isConnect = true;
    }
}

void NetWorkController::m_sendLoginMessage(const QString &username , const QString &password)

{

    QJsonObject message;
    message.insert("cmd",LOGIN);
    message.insert("username",username);
    message.insert("password",password);
    QJsonDocument data(message);
    qint64 bytesWritten = cSocket->write(data.toJson());
    if(bytesWritten!=-1)
    {
        qDebug()<<"发送数据成功";
    }
    else
    {
        qDebug()<<"发送数据失败";
    }
    if (!cSocket->waitForReadyRead(15000)) {
        QMessageBox::warning(nullptr,"warning","服务器未响应");
    }else{
        QByteArray res = cSocket->readAll();
        qDebug()<<res;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(res);
        QJsonObject resObj = jsonDoc.object();

        switch (resObj["cmd"].toInt()) {
        case LOGIN_SUCCESS:
            qDebug()<<"login success";
            UserInfo::getInstance()->setUserName(resObj["username"].toString());
            UserInfo::getInstance()->setUid(resObj["uid"].toString());
            PageController::Getinstance()->showQQWindow();
            break;
        case LOGIN_ALREADY_DO:

            break;
        case LOGIN_USER_NONEXISTENCE:

            break;
        default:
            break;
        }
    }
}

QString NetWorkController::generateCaptcha()
{
    // 生成随机验证码的逻辑
    return QString::number(QRandomGenerator::global()->bounded(100000, 999999));
}

bool NetWorkController::sendCaptchaEmail(const QString &recipient, const QString &captcha)
{
    QTcpSocket socket;
    socket.connectToHost("smtp.qq.com", 25); // 使用普通的 SMTP 端口 25

    if (!socket.waitForConnected()) {
        qDebug() << "Failed to connect to SMTP server";
        return false;
    }

    // 读取服务器返回的欢迎消息
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed to read welcome message from SMTP server";
        return false;
    }
    qDebug() << "Server response:" << socket.readAll();

    // 发送 EHLO 命令
    socket.write("EHLO localhost\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after EHLO command";
        return false;
    }
    qDebug() << "Sent EHLO command";
    qDebug() << "Server response after EHLO:" << socket.readAll();

    // 发送 AUTH LOGIN 命令
    socket.write("AUTH LOGIN\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after AUTH LOGIN command";
        return false;
    }
    qDebug() << "Sent AUTH LOGIN command";
    qDebug() << "Server response after AUTH LOGIN:" << socket.readAll();

    // 发送 Base64 编码的用户名
    QByteArray username = QByteArray("2474692739@qq.com").toBase64();
    socket.write(username + "\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after sending username";
        return false;
    }
    qDebug() << "发送 username";
    qDebug() << "输入username后的服务器响应:" << socket.readAll();

    // 发送 Base64 编码的授权码
    QByteArray password = QByteArray(SMTPCODE).toBase64();
    socket.write(password + "\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "发送密码失败";
        return false;
    }
    // qDebug() << "发送密码";
    //qDebug() << "输入密码后的服务器响应:" << socket.readAll();

    // 发送 MAIL FROM 命令
    socket.write("MAIL FROM:<2474692739@qq.com>\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after MAIL FROM command";
        return false;
    }
    // qDebug() << "Sent MAIL FROM command";
    // qDebug() << "Server response after MAIL FROM:" << socket.readAll();

    // 发送 RCPT TO 命令
    socket.write(QString("RCPT TO:<%1>\r\n").arg(recipient).toUtf8());
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after RCPT TO command";
        qDebug() << "Server response after RCPT TO:" << socket.readAll();
        return false;
    }
    // qDebug() << "Sent RCPT TO command";
    //qDebug() << "Server response after RCPT TO:" << socket.readAll();

    // 发送 DATA 命令
    socket.write("DATA\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after DATA command";
        return false;
    }
    //qDebug() << "Sent DATA command";
    // qDebug() << "Server response after DATA:" << socket.readAll();

    // 发送邮件头部和正文
    socket.write("From: <2474692739@qq.com>\r\n");
    socket.write(QString("To: <%1>\r\n").arg(recipient).toUtf8());
    socket.write("Subject: Verification Code\r\n");
    socket.write("Content-Type: text/plain; charset=utf-8\r\n");
    socket.write("\r\n");  // 头部结束，正文开始
    socket.write(QString("你的验证码是: %1\r\n").arg(captcha).toUtf8());
    socket.write(".\r\n");  // 邮件正文结束标志
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after sending email body";
        return false;
    }
    // qDebug() << "Sent email body";
    //qDebug() << "Server response after email body:" << socket.readAll();

    // 发送 QUIT 命令
    socket.write("QUIT\r\n");
    socket.waitForBytesWritten();
    if (!socket.waitForReadyRead()) {
        qDebug() << "Failed after QUIT command";
        return false;
    }
    qDebug() << "Sent QUIT command";
    qDebug() << "Server response after QUIT:" << socket.readAll();

    socket.close(); // 关闭连接
    return true;
}

void NetWorkController::sendRegisterMessage(const QString &username , const QString &password)
{
    QJsonObject message;
    message.insert("cmd",REGISTER);
    message.insert("username",username);
    message.insert("password",password);
    QJsonDocument data(message);
    qint64 bytesWritten = cSocket->write(data.toJson());
    if(bytesWritten!=-1)
    {
        qDebug()<<"发送数据成功";
    }
    else
    {
        qDebug()<<"发送数据失败";
    }
    if (!cSocket->waitForReadyRead(15000)) {
        QMessageBox::warning(nullptr,"warning","服务器未响应");
    }else{
        QByteArray res = cSocket->readAll();
        qDebug()<<res;
        QJsonDocument jsonDoc = QJsonDocument::fromJson(res);
        QJsonObject resObj = jsonDoc.object();
        switch (resObj["cmd"].toInt()) {
        case REGISTER_SUCCESS:
            QMessageBox::information(nullptr,"提示","注册成功");
            break;
        case REGISTER_USER_EXIST:
            QMessageBox::warning(nullptr,"警告","用户已存在");
            break;
        default:
            break;
        }
    }
}

bool NetWorkController::sendAddFrdMessage(const QString &username)
{
    QJsonObject message;
    message.insert("cmd",ADD_FRIEND);
    message.insert("username",username);
    QJsonDocument data(message);
    qint64 bytesWritten = cSocket->write(data.toJson());
    if(bytesWritten!=-1)
    {
        qDebug()<<"发送数据成功addfrd";
        return true;
    }
    else
    {
        qDebug()<<"发送数据失败addfrd";
        return false;
    }
}

bool NetWorkController::sendChatMessage(const QString &username,const QString &text)
{
    QJsonObject message;
    message.insert("cmd",CHAT_MESSAGE);
    message.insert("username",username);
    message.insert("message",text);
    QJsonDocument data(message);
    qint64 bytesWritten = cSocket->write(data.toJson());
    qDebug()<<data.toJson();
    if(bytesWritten!=-1)
    {
        qDebug()<<"发送数据成功addfrd";
        return true;
    }
    else
    {
        QString errorMessage = QString("发送数据失败: %1").arg(cSocket->errorString());
        qDebug() << errorMessage;
        return false;
    }
}
void NetWorkController::client_Recv()
{
    QByteArray response = cSocket->readAll();
    qDebug()<<response;
    QJsonDocument jsonDoc = QJsonDocument::fromJson(response);
    QJsonObject resObj = jsonDoc.object();
    QJsonArray friendsArray;
    QString chatUsername;
    QString chatMessage;

    switch (resObj["cmd"].toInt()) {
    case FRIEND:
       friendsArray = resObj["friends"].toArray();
        sendFriendInfo(friendsArray);
        break;
    case CHAT_RECV:
        chatUsername = resObj["username"].toString();
        chatMessage = resObj["message"].toString();
        sendMsgSig(chatUsername,chatMessage);
        break;

    }
}

NetWorkController::NetWorkController()
{

}

QTcpSocket *NetWorkController::getCSocket() const
{
    return cSocket;
}

void NetWorkController::setCSocket(QTcpSocket *newCSocket)
{
    cSocket = newCSocket;
}



bool NetWorkController::getIsConnect() const
{
    return isConnect;
}

void NetWorkController::setIsConnect(bool newIsConnect)
{
    isConnect = newIsConnect;
}
